package com.linkgie.galaxyframework.httpproxy.converters;

import java.io.InputStream;
import java.io.OutputStream;

import com.linkgie.galaxyframework.httpproxy.HttpRequestDefinition;
import com.linkgie.galaxyframework.httpproxy.ResponseHandler;
import com.linkgie.galaxyframework.httpproxy.ResponseHandlerFactory;

public class DefaultResponseHandlerFactory implements ResponseHandlerFactory {

	public static final DefaultResponseHandlerFactory INSTANCE = new DefaultResponseHandlerFactory();

	public static final ResponseHandler DEFAULT_ERROR_HANDLER = HttpErrorResponseHandler.INSTANCE;

	private DefaultResponseHandlerFactory() {
	}

	@Override
	public ResponseHandler createResponseHandler(HttpRequestDefinition requestDefinition, Class<?> returnType) {
		// create default response converter;
		ResponseHandler successHandler;

		if (Void.class.equals(returnType)) {
			successHandler = NullResponseHandler.INSTANCE;
		} else if (Object.class == returnType || String.class == returnType) {
			successHandler = StringResponseHandler.INSTANCE;
		} else if (byte[].class == returnType) {
			successHandler = ByteArrayResponseHandler.INSTANCE;
		} else if (int.class == returnType || Integer.class == returnType) {
			successHandler = IntegerResponseHandler.INSTANCE;
		} else if (long.class == returnType || Long.class == returnType) {
			successHandler = LongResponseHandler.INSTANCE;
		} else if (double.class == returnType || Double.class == returnType) {
			successHandler = DoubleResponseHandler.INSTANCE;
		} else if (boolean.class == returnType || Boolean.class == returnType) {
			successHandler = BooleanResponseHandler.INSTANCE;
		} else if (InputStream.class == returnType) {
			successHandler = InputStreamResponseHandler.INSTANCE;
		} else if (OutputStream.class == returnType) {
			throw new IllegalArgumentException(
					"Unsupported return type[" + OutputStream.class.getName() + "]!");
		} else {
			successHandler = new JsonResponseHandler(returnType);
		}

		return new DefaultResponseHandler(successHandler, DEFAULT_ERROR_HANDLER);
	}

}
